import { Block, Button, Icon, ScrollView, View } from '@tarojs/components';
import {
  hideLoading,
  previewImage,
  redirectTo,
  showLoading,
  showModal,
  showToast,
  switchTab,
  useEffect,
  useRef,
  useRouter,
  useState
} from '@tarojs/taro';
import Layout from '../../components/Layout';
import XEditor from '../../components/XEditor';
import XFilter from '../../components/XFilter';
import XInput from '../../components/XInput';
import XList from '../../components/XList';
import XRow from '../../components/XRow';
import { CacheLastProductId } from '../../constant/cache';
import { bugTypesArray, bugTypesValueArray, priArray, priValueArray } from '../../constant/label';
import baseService from '../../utils/baseService';
import upload from '../../utils/upload';
import { formatHtml, getCache, setCache } from '../../utils/utils';

const Edit = () => {
  const defaultSteps = '[步骤]<br><br>[结果]<br><br>[期望]<br><br>';
  const [curr, setCurr] = useState({
    steps: defaultSteps,
    productIndex: 0,
    typeIndex: 0,
    priIndex: 1
  });
  const [products, setProducts] = useState([[]]);
  const [users, setUsers] = useState([[]]);
  const [modules, setModules] = useState([[]]);
  const [files, setFiles] = useState([]);
  const [isShowEditor, setIsShowEditor] = useState(false);
  const userValues = useRef([]);
  const productsValues = useRef([]);
  const modulesValues = useRef([]);
  const lastProductId = getCache(CacheLastProductId);
  const submitFiled = [
    'product',
    'title',
    'openedBuild',
    'branch',
    'module',
    'project',
    'assignedTo',
    'deadline',
    'type',
    'os',
    'browser',
    'color',
    'severity',
    'pri',
    'steps',
    'mailto',
    'keywords'
  ];
  const {
    params: { id }
  } = useRouter();

  useEffect(() => {
    if (id) {
      getProducts(() => {
        getRow(({ bug }) => {
          const { product } = bug;
          onGetInit(product, () => {
            //将结果转为索引值
            const { product, pri, type, assignedTo, module } = bug;
            const o = {};
            o['productIndex'] = productsValues.current.findIndex((x) => x === product);
            o['assignedToIndex'] = userValues.current.findIndex((x) => x === assignedTo);
            o['typeIndex'] = bugTypesValueArray.findIndex((x) => x === type);
            o['priIndex'] = priValueArray.findIndex((x) => x === pri);
            o['moduleIndex'] = modulesValues.current.findIndex((x) => x === module);
            setCurr({ ...bug, ...o });
          });
        });
      });
    } else {
      getProducts();
      if (lastProductId) {
        onGetInit(lastProductId, () => {
          const pIndex = productsValues.current.findIndex((x) => x === lastProductId);
          setCurr({ ...curr, product: lastProductId, productIndex: pIndex });
        });
      }
    }
  }, []);

  const getRow = (cb = null) => {
    showLoading({ title: '操作中' });
    baseService.query('/bug-view-' + id + '-.json', {}).then(({ data }) => {
      console.log(data);
      const arr = formatHtml(data['bug']['steps'] || '').split('[图片附件]');
      console.log(1, arr);
      const body = arr[0] || '';
      const imgs = arr[1] || '';
      let fs = imgs
        .split(/<br>|<br \/>/gi)
        .filter((x) => x)
        .map((x) => {
          const url = (x.match(/(http.[^"]+)/gi) || []).join('');
          return { url, html: x };
        });
      data['bug']['steps'] = body;
      setCurr(data['bug']);
      setFiles(fs);
      hideLoading();
      cb && cb(data);
    });
  };

  const getProducts = (cb = null) => {
    baseService.query('/product-all---noclosed---100.json', {}).then(({ data }) => {
      const { productStats = [] } = data;
      console.log(data);
      const pids = productStats.map((x) => x['id']);
      setProducts([['请选择'].concat(productStats.map((x) => x['name']))]);
      productsValues.current = [''].concat(pids);
      if (lastProductId) {
        setCurr({ ...curr, productIndex: pids.findIndex((x) => x === lastProductId) + 1 });
      }
      cb && cb(data);
    });
  };

  const onChange = (key, e) => {
    const value = e.detail.value;
    setCurr({ ...curr, [key]: value });
  };

  const onChangeFilter = (key, groupIndex, value, index) => {
    let vl = null;
    switch (key) {
      case 'product':
        vl = productsValues.current[index];
        setCache(CacheLastProductId, vl);
        onGetInit(vl);
        break;
      case 'module':
        vl = modulesValues.current[index];
        break;
      case 'assignedTo':
        vl = userValues.current[index];
        break;
      case 'type':
        vl = bugTypesValueArray[index];
        break;
      case 'pri':
        vl = priValueArray[index];
        break;
    }
    setCurr({ ...curr, [key]: vl, [key + 'Index']: index });
  };

  const onGetInit = (id, cb = null) => {
    showLoading({ title: '操作中' });
    baseService
      .query(`/bug-create-${id}-0-moduleID=0.json`, {})
      .then(({ data }) => {
        const { projectMembers, users, moduleOptionMenu } = data;
        console.log(data);
        const us = id ? users : projectMembers;
        setUsers([Object.values(us)]);
        userValues.current = Object.keys(us);
        setModules([Object.values(moduleOptionMenu)]);
        modulesValues.current = Object.keys(moduleOptionMenu);
        hideLoading();
        cb && cb();
      })
      .catch((error) => {
        console.error(error);
        showToast({ title: '加载初始化数据失败', icon: 'none' });
        hideLoading();
      });
  };

  const onUpload = () => {
    upload({})
      .then((url) => {
        const fs = [...files];
        fs.push({
          url,
          html: `<img src="${url}" style="max-width:100%;height:auto;display:block;">`
        });
        setFiles(fs);
      })
      .catch((error) => {
        console.error(error);
      });
  };

  const onPreview = (url) => {
    previewImage({
      current: url,
      urls: files.map((x) => x.url)
    });
  };

  const onCloseImg = (index) => {
    showModal({ title: '操作提示', content: '确定要删除图片吗' }).then(({ confirm }) => {
      if (confirm) {
        const fs = [...files];
        fs.splice(index, 1);
        setFiles(fs);
      }
    });
  };

  const onSave = () => {
    if (!curr['product']) {
      showToast({ title: '请选择产品', icon: 'none' });
      return;
    }
    if (!curr['title']) {
      showToast({ title: '请输入标题', icon: 'none' });
      return;
    }

    if (!curr['assignedTo']) {
      showToast({ title: '请选择指派人', icon: 'none' });
      return;
    }

    showLoading({ title: '操作中' });

    //处理非必要字段否则会报错
    const record = { ...curr };
    Object.keys(record).forEach((x) => {
      if (!submitFiled.includes(x)) {
        delete record[x];
      }
    });
    const url = id
      ? `/bug-edit-${id}.json`
      : `/bug-create-${record['product'] ||
          productsValues.current[0]}-0-moduleID=0.json`;
    baseService
      .post(
        url,
        {
          product: parseInt(productsValues.current[0]),
          type: bugTypesValueArray[0],
          assignedTo: userValues.current[0],
          pri: priValueArray[1],
          openedBuild: 'trunk',
          os: 'windows',
          browser: 'all',
          severity: '3',
          ...record,
          steps:
            (record['steps'] || defaultSteps) +
            (files.length ? '<br><br>[图片附件]<br>' + files.map((x) => x.html).join('<br>') : '') +
            '<br />来自oa的bug'
        },
        { isForm: true }
      )
      .then(({ data }) => {
        console.log('创建bug', data);
        showToast({ title: '保存成功' });
        if (id) {
          redirectTo({ url: 'detail?id=' + id });
        } else {
          switchTab({ url: 'index' });
        }
      })
      .catch(() => {
        showToast({ title: '保存失败', icon: 'none' });
        hideLoading();
      });
  };

  const onClickSteps = () => {
    setIsShowEditor(true);
  };

  const onCommitEditor = ({ html, text }) => {
    onChange('steps', { detail: { value: html } });
    setIsShowEditor(false);
  };

  return (
    <Layout>
      {isShowEditor && <XEditor onCommit={onCommitEditor} value={curr['steps'] || ''}></XEditor>}
      <ScrollView
        scrollY={true}
        style={{ height: 'calc(100vh - 50px - env(safe-area-inset-bottom))' }}
      >
        <View style={{ paddingBottom: '50px' }}>
          <XList isCustomize={true} isMini={true}>
            <XRow>
              <View>产品</View>
              <XFilter
                filterOptions={products}
                value={curr['productIndex']}
                onChange={onChangeFilter.bind(this, 'product')}
              ></XFilter>
            </XRow>
          </XList>
          {curr['product'] && (
            <Block>
              <XList isCustomize={true}>
                <XInput
                  label="标题"
                  placeholder="简单明了的标题"
                  value={curr['title']}
                  onChange={onChange.bind(this, 'title')}
                ></XInput>
              </XList>
              <XList isCustomize={true} isMini={true}>
                <XRow>
                  <View>模块</View>
                  <XFilter
                    filterOptions={modules}
                    value={curr['moduleIndex']}
                    onChange={onChangeFilter.bind(this, 'module')}
                  ></XFilter>
                </XRow>
              </XList>
              <XList isCustomize={true} isMini={true}>
                <XRow>
                  <View>指派给</View>
                  <XFilter
                    filterOptions={users}
                    value={curr['assignedToIndex']}
                    onChange={onChangeFilter.bind(this, 'assignedTo')}
                  ></XFilter>
                </XRow>
              </XList>
              <XList isCustomize={true} isMini={true}>
                <XRow>
                  <View>类型</View>
                  <XFilter
                    filterOptions={bugTypesArray}
                    value={curr['typeIndex']}
                    onChange={onChangeFilter.bind(this, 'type')}
                  ></XFilter>
                </XRow>
              </XList>
              <XList isCustomize={true} isMini={true}>
                <XRow>
                  <View>优先级</View>
                  <XFilter
                    filterOptions={priArray}
                    value={curr['priIndex']}
                    onChange={onChangeFilter.bind(this, 'pri')}
                  ></XFilter>
                </XRow>
              </XList>
              <XList isCustomize={true} isMini={true}>
                <XRow>
                  <View>上传图片</View>
                  <View style={{ display: 'flex', alignItems: 'center' }}>
                    <Button size="mini" type="warn" onClick={onUpload}>
                      上传
                    </Button>
                  </View>
                </XRow>
                <View style={{ display: 'flex', alignItems: 'center' }}>
                  {files.map((x, xIndex) => (
                    <View key={x.url} style={{ marginRight: '2px', position: 'relative' }}>
                      <Image
                        src={x.url}
                        style={{ width: '60px', height: '60px' }}
                        onClick={onPreview.bind(this, x)}
                      ></Image>
                      <Icon
                        type="clear"
                        color="red"
                        size="16"
                        style={{ position: 'absolute', right: '0' }}
                        onClick={onCloseImg.bind(this, xIndex)}
                      ></Icon>
                    </View>
                  ))}
                </View>
              </XList>
              <XList isCustomize={true} onClick={onClickSteps}>
                <wxparser rich-text={curr['steps'] || ''} />
              </XList>
            </Block>
          )}
        </View>
      </ScrollView>

      <View
        style={{
          position: 'fixed',
          bottom: 0,
          marginBottom: 0,
          width: '100%',
          background: '#23d1a5',
          color: '#fff',
          zIndex: 10000,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          paddingTop: '14px',
          paddingBottom: 'calc(14px + env(safe-area-inset-bottom))'
        }}
        onClick={onSave}
      >
        保存
      </View>
    </Layout>
  );
};
Edit.config = {
  navigationBarTitleText: '提BUG',
  disableScroll: true,
  usingComponents: {
    wxparser: 'plugin://wxparserPlugin/wxparser'
  }
};
export default Edit;
